package com.hu.bgp.server;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.hu.bgp.client.ClientGameContext;
import com.hu.bgp.client.rpc.BgpService;
import com.hu.bgp.framework.ServerFacade;
import com.hu.bgp.framework.clientapi.GameID;
import com.hu.bgp.shared.data.ClientGameSession;
import com.hu.bgp.shared.data.ClientGameSessionCollection;
import com.hu.bgp.shared.data.ClientGameType;
import com.hu.bgp.shared.data.ClientGameTypeCollection;

public class BgpServiceImpl extends RemoteServiceServlet implements BgpService
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 5351684402376422832L;

	public void joinGame(GameID gameId)
	{
		//TODO to be implemented
		GameServerContext gsc = GameServerContext
		.getInstance(getServletContext());
		
		gsc.getGameInstance(gameId);
		//then join game
		
	}

	public ClientGameContext getClientGameContext(GameID gameID)
	{
		GameServerContext gsc = GameServerContext
				.getInstance(getServletContext());

		ServerFacade game= gsc.getGameInstance(gameID);
		GameContext gc = (com.hu.bgp.server.GameContext) game.getGameContext();
		return new ClientGameContext(gc.getGameDomain(), gc.getGameDomain());
	}

	public ClientGameTypeCollection getClientGameTypeCollection() {
		GameServerContext gsc = GameServerContext
				.getInstance(getServletContext());

		ClientGameTypeCollection result = new ClientGameTypeCollection();
		for (GameType gt : gsc.getGameTypeCollection()) {
			if (gt.isActive())
				result.add(new ClientGameType(gt.getAlias(), gt
						.getDisplayName(), gt.getDescription(), gt.isActive()));
		}

		return result;
	}

	public ClientGameSession createGame(String gameAlias)
	{
		GameServerContext gsc = GameServerContext
				.getInstance(getServletContext());
	
		String sid = getThreadLocalRequest().getSession().getId();
		ServerFacade game = gsc.initGameInstance(sid, gameAlias);
		ClientGameSession ret = new ClientGameSession();
		ret.setGameID(game.getGUID());
		return ret;
	}

	public void login(String username, String password) {
		String sid = getThreadLocalRequest().getSession(true).getId();
	}

	public ClientGameSessionCollection getClientGameSessionCollection(
			String gameAlias) {
		GameServerContext gsc = GameServerContext.getInstance(getServletContext());
		GameType gt = gsc.getGameTypeByAlias(gameAlias);
		ClientGameSessionCollection result = new ClientGameSessionCollection();
		for (String s : gt.getRunningGames()) {
			ClientGameSession cs =new ClientGameSession();
			cs.setGameID(s);
			cs.setGameName("id's only");
				result.add(cs);
			}
		
		return result;
	}

}
